package com.codemart.lanze.modules.sys.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codemart.lanze.modules.sys.mapper.RoleMapper;
import com.codemart.lanze.modules.sys.mapper.RolePermissionMapper;
import com.codemart.lanze.modules.sys.model.Role;
import com.codemart.lanze.modules.sys.model.RolePermission;

/**
 * @description:
 * @author: lanze
 */
@Transactional
@Service
public class RoleService extends ServiceImpl<RoleMapper, Role> {

	@Resource
	private RoleMapper roleMapper;
	@Resource
	private RolePermissionMapper rolePermissionMapper;

	/**
	 * 根据角色名称查询角色对象信息
	 *
	 * @param name
	 * @return
	 */
	@Transactional(readOnly = true)
	public Role findByName(String name) {
		QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("name", name);
		return this.getOne(queryWrapper);
	}

	/**
	 * 根据用户ID查询角色对象信息
	 *
	 * @param userId
	 * @return
	 */
	public Role findByUserId(Long userId) {
		return roleMapper.findByUserId(userId);
	}

	/**
	 * 根据角色ID删除角色并级联删除该角色和权限的关联信息
	 *
	 * @param roleId
	 * @return
	 */
	public Boolean deleteRoleAndRolePermissionByRoleId(Long roleId) {
		// 先删级联表再删主表
		// 级联删除该角色所关联的权限
		QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("role_id", roleId);
		rolePermissionMapper.delete(queryWrapper);

		// 删除角色
		boolean count = this.removeById(roleId);

		return count;
	}

	public IPage<Role> findPageListByWhere(Integer pageNum, Integer pageSize, Role role) {
		QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
		if (role != null) {
			queryWrapper.eq("role_id", role.getId());
		}
		IPage<Role> iPage = this.page(new Page<>(pageNum, pageSize), queryWrapper);
		return iPage;
	}
}
